package com.yuncheng.spcyApi.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yuncheng.spcyApi.entity.SpcyKpNdpxjl;
import com.yuncheng.spcyApi.entity.SysUserPxjl;
import com.yuncheng.spcyApi.mapper.SpcyKpNdpxjlMapper;
import com.yuncheng.spcyApi.service.ISpcyKpNdpxjlService;
import com.yuncheng.spcyApi.utils.GetUuIdUtils;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import com.yuncheng.common.base.service.impl.BaseServiceImpl;

import java.lang.reflect.InvocationTargetException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Optional;

/**
 * @Description: 检查员-年度考评培训记录
 * @Author: yuncheng
 * @Date: 2024-02-23
 * @Version: V1.0
 */
@Service
public class SpcyKpNdpxjlServiceImpl extends BaseServiceImpl<SpcyKpNdpxjlMapper, SpcyKpNdpxjl> implements ISpcyKpNdpxjlService {

    @Override
    public String getTotalLearningHoursTheCurrentYearByNdkpId(String fndkpid) {
        if (StringUtils.isBlank(fndkpid)){
            return "0";
        }

        List<SpcyKpNdpxjl> list = list(new LambdaQueryWrapper<SpcyKpNdpxjl>()
                .eq(SpcyKpNdpxjl::getFndkpid, fndkpid));

        BigDecimal totalLearningHours = new BigDecimal("0");
        for (SpcyKpNdpxjl pxjl : list){
            totalLearningHours = totalLearningHours.add(new BigDecimal(Optional.ofNullable(pxjl.getFpxxs()).orElseGet(()->"0")));
        }
        return totalLearningHours.toString();
    }

    @Override
    public void genNdPxjl(List<SysUserPxjl> userPxjlList, String fndkpid) throws InvocationTargetException, IllegalAccessException {
        if (CollectionUtil.isEmpty(userPxjlList)){
            return;
        }

        SpcyKpNdpxjl nd = null;
        for (SysUserPxjl bean : userPxjlList){

            List<SpcyKpNdpxjl> pxList = list(new LambdaQueryWrapper<SpcyKpNdpxjl>()
                    .eq(SpcyKpNdpxjl::getFndkpid, fndkpid)
                    .eq(SpcyKpNdpxjl::getFpxjlid, bean.getId()));
            if (CollectionUtil.isNotEmpty(pxList)){
                continue;
            }

            nd = new SpcyKpNdpxjl();
            BeanUtils.copyProperties(nd, bean);

            nd.setId(GetUuIdUtils.ReplaceUuId());
            nd.setFpxjlid(bean.getId());
            nd.setFndkpid(fndkpid);

            nd.setCreateTime(new Date());
            nd.setUpdateTime(new Date());


            save(nd);
        }
    }

    @Override
    public List<SpcyKpNdpxjl> getNdpxjlByNdkpId(String fndkpid) {
        if (StringUtils.isBlank(fndkpid)){
            return new ArrayList<>(1);
        }

        return list(new LambdaQueryWrapper<SpcyKpNdpxjl>()
                .eq(SpcyKpNdpxjl::getFndkpid, fndkpid));
    }

    @Override
    public void deleteNdpxjlById(String id) {
        removeById(id);
    }
}
